package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysUserInfo;
import com.itheima.ydd.dto.UserDto;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.service.RoleService;
import com.itheima.ydd.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys_user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 用户列表-分页
     *
     * @param name
     * @param status
     * @param phone
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public ResultData list(@RequestParam("login_name") String name, Integer status, String phone, Long page, @RequestParam("limit") Long pageSize) {
        //创建分页构造器
        Page<User> userPage = new Page<>(page, pageSize);
        //创建条件构造器
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(phone != "", User::getPhone, phone);
        lqw.eq(status != null, User::getStatus, status);
        lqw.like(name != "", User::getLogin_name, name);
        userService.page(userPage, lqw);
        List<User> records = userPage.getRecords();

        Page<SysUserInfo> infoPage = new Page<>();
        BeanUtils.copyProperties(userPage, infoPage, "records");

        List<SysUserInfo> userInfos = records.stream().map(user -> {
            SysUserInfo userInfo = new SysUserInfo();
            BeanUtils.copyProperties(user, userInfo);
            String role_id = user.getRole_id();
            String s = role_id.substring(1, role_id.length() - 1);
            String substring = s.substring(1, s.length() - 1);
            System.out.println(s);
            userInfo.setRolename(roleService.roleNameList(substring));
            return userInfo;
        }).collect(Collectors.toList());
        infoPage.setRecords(userInfos);
        PageResult pageResult = PageResult.init(userPage.getTotal(), page, pageSize, infoPage.getRecords());
        return ResultData.ok("200", pageResult);
    }

    /**
     * 管理员删除
     *
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(String id) {
        userService.removeById(id);
        return ResultData.ok("200", 200);
    }

    /**
     * 管理员添加
     *
     * @param user
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody UserDto user) {
        log.info("user= {}", user);

        List<String> roleId = user.getRole_id();
        String role_id = "[\"";
        for (String s : roleId) {
            s += ",";
            role_id += s;
        }
        role_id += "1";
        int index = role_id.lastIndexOf(",");
        System.out.println(index);
        char[] chars = role_id.toCharArray();
        chars[index] = '"';
        chars[index + 1] = ']';
        role_id = String.valueOf(chars);
        User user1 = new User();
        BeanUtils.copyProperties(user, user1, "role_id");
        user1.setRole_id(role_id);
        userService.save(user1);
        return ResultData.ok("添加成功", 200);
    }

    /**
     * 管理员详情
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {
        log.info("id={}", id);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId, id);
        User one = userService.getOne(lqw);
        //查询用户角色id集合: role_id
        String[] rowIds = one.getRole_id().replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        List<String> ids = new ArrayList<>();
        Collections.addAll(ids, rowIds);

        SysUserInfo userInfo = new SysUserInfo();
        BeanUtils.copyProperties(one, userInfo);
        userInfo.setRole_id(ids);
        return ResultData.ok("200", userInfo);
    }

    /**
     * 管理员修改
     *
     * @param sysUserInfo
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody SysUserInfo sysUserInfo) {
        log.info("user={}", sysUserInfo);
        List<String> roleId = sysUserInfo.getRole_id();
        if (roleId != null) {
            String role_id = "[\"";
            for (String s : roleId) {
                s += ",";
                role_id += s;
            }
            role_id += "1";
            int index = role_id.lastIndexOf(",");
            System.out.println(index);
            char[] chars = role_id.toCharArray();
            chars[index] = '"';
            chars[index + 1] = ']';
            role_id = String.valueOf(chars);

            log.info("参数:{}", role_id);
            //封装数据
            User user = new User();
            user.setId(sysUserInfo.getId());
            user.setLogin_name(sysUserInfo.getLogin_name());
            user.setPassword(sysUserInfo.getPassword());
            user.setName(sysUserInfo.getName());
            user.setEmail(sysUserInfo.getEmail());
            user.setPhone(sysUserInfo.getPhone());
            user.setLogin_ip(sysUserInfo.getLogin_ip());
            user.setCreate_date(sysUserInfo.getCreate_date());
            user.setUpdate_date(sysUserInfo.getUpdate_date());
            user.setDel_flag(sysUserInfo.getDel_flag());
            user.setRole_id(role_id);
            user.setStatus(sysUserInfo.getStatus());
            user.setDefault_data(sysUserInfo.getDefault_data());

            //修改数据
            userService.updateById(user);

            //  userService.updateById(user);
            return ResultData.ok("修改成功", null);
        } else {
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId, sysUserInfo.getId());
            updateWrapper.set(User::getStatus, sysUserInfo.getStatus());
            userService.update(updateWrapper);
            return ResultData.ok("修改成功", null);
        }
    }
}
